package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname DishServiceImpl
 * @Description
 * @Version 1.0.0
 * @Date 2024/6/23 19:57
 * @Created by Ren
 */
@Slf4j
@Service
public class DishServiceImpl implements DishService {

    @Resource
    private DishMapper dishMapper;
    @Resource
    private DishFlavorMapper dishFlavorMapper;
    @Resource
    private SetmealDishMapper setmealDishMapper;
    @Resource
    private CategoryMapper categoryMapper;

    @Override
    @Transactional
    public void addDish(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);


        try {
            dishMapper.addDish(dish);  //想菜品表插入一条数据

            List<DishFlavor> dishFlavorList = dishDTO.getFlavors();  //添加完菜品之后才能有 dishId 所以放到这里

            //list为空 或者 长度为 0 说明没有菜品口味直接结束函数
            if (dishFlavorList == null || dishFlavorList.size() == 0) {
                return;
            }

            for (DishFlavor dishFlavor : dishFlavorList) {  //为每个口味设置菜品ID
                dishFlavor.setDishId(dish.getId());
            }
            dishFlavorMapper.insertBatch(dishFlavorList);   //向口味表批量插入数据

        } catch (Exception e) {
            log.info("新增菜品和口味失败...{}", e.getMessage());
        }

    }

    @Override
    public PageResult queryPage(DishPageQueryDTO dishPageQueryDTO) {
//        // 计算起始索引
//        int offset = (dishPageQueryDTO.getPage() - 1) * dishPageQueryDTO.getPageSize();
//
//        // 创建一个包含分页参数的 Map
//        HashMap<String, Object> params = new HashMap<>();
//        params.put("offset", offset);
//        params.put("pageSize", dishPageQueryDTO.getPageSize());

        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> dishVOS = dishMapper.pageQuery(dishPageQueryDTO);


        return new PageResult(dishVOS.getTotal(), dishVOS.getResult());
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {

        //判断当前菜品是否能够删除---是否在起售中的菜品？？？
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                //当前菜品处于起售中,不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //判断当前菜品是否能够删除---是否被套餐关联了？？？
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            //说明菜品和套餐有关联不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }


        //删除菜品表中的菜品数据
        dishMapper.deleteBatch(ids);

        //删除口味表中菜品关联的口味数据

        dishFlavorMapper.deleteBatch(ids);


    }

    @Override
    public DishVO getDishWithFlavorById(Long id) {

        //得到菜品数据
        Dish dish = dishMapper.getById(id);
        //得到分类名称
        Category category = categoryMapper.getCategoryById(dish.getCategoryId());
        //根据菜品id再得到口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getDishFlavorByDishId(dish.getId());

        //构造返回的数据
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setCategoryName(category.getName());
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    @Override
    @Transactional
    public void updateDishWithFlavorById(DishDTO dishDTO) {


        try {
            //修改菜品信息
            Dish dish = new Dish();
            BeanUtils.copyProperties(dishDTO, dish);
            dishMapper.updateDishById(dish);

            //修改菜品对应的口味信息
            //先删除，然后再添加
            dishFlavorMapper.deleteDishFlavorByDishId(dishDTO.getId());
            List<DishFlavor> dishFlavorList = dishDTO.getFlavors();

            if (!dishFlavorList.isEmpty()) {
                //dishFlavorList不为空才能进行赋值和插入
                for (DishFlavor dishFlavor : dishFlavorList) {
                    dishFlavor.setDishId(dishDTO.getId());
                }
                dishFlavorMapper.insertBatch(dishDTO.getFlavors());
            }
        } catch (Exception e) {
            throw new RuntimeException("修改菜品信息错误 " + e.getMessage());
        }

    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getDishFlavorByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
    public void startOrStop(Integer status, Long id){
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.updateDishById(dish);
    }
}
